from django.shortcuts import render
from django.views import View
from .models import Book
from cart.models import Cart


class BookListView(View):
    def get(self, request):
        # 从数据库取数据
        books = Book.objects.all()
        return render(
            request,
            'book/list.html',
            {
                'books': books,
            }
        )


class BookDetailView(View):
    def get(self, request, book_id):
        book = Book.objects.get(pk=book_id)

        if request.user.is_authenticated:
            paid_book = Cart.objects.filter(
                user_id=request.user.id, book_id=book_id).first()
            is_paid = True if (paid_book and paid_book.paid) else False
        else:
            is_paid = False

        return render(
            request,
            'book/detail.html',
            {
                'book': book,
                'is_paid': is_paid,
            }
        )
